package com.skyolder.crutch.word.token.raw;

import java.util.ArrayList;

import com.skyolder.crutch.error.GrammarError;
import com.skyolder.crutch.word.raw.BufferCharPiper;
import com.skyolder.crutch.word.raw.BufferCharQueue;
import com.skyolder.crutch.word.raw.StringHelper;
import com.skyolder.crutch.word.types.RawTokenType;

public class KeyWordTokenTokenCreator implements TokenCreator {
	private String[] keys = new String[] { "if", "elif", "else", "for", "while", "var", "function", "int", "long",
			"double", "string", "null", "bool", "byte", "char", "void", "global", "include", "namespace", "return",
			"continue", "break", "new" };
	private String[] k_1 = new String[] {};
	private String[] k_2 = new String[] { "if" };
	private String[] k_3 = new String[] { "for", "var", "int", "new" };
	private String[] k_4 = new String[] { "elif", "else", "long", "null", "bool", "byte", "char", "void" };
	private String[] k_5 = new String[] { "while", "break" };
	private String[] k_6 = new String[] { "double", "string", "global", "return" };
	private String[] k_7 = new String[] { "include", "include" };
	private String[] k_8 = new String[] { "function", "continue" };
	private String[] k_9 = new String[] { "namespace" };
	private ArrayList<String[]> arrayList = new ArrayList<String[]>();
	{
		arrayList.add(k_1);
		arrayList.add(k_2);
		arrayList.add(k_3);
		arrayList.add(k_4);
		arrayList.add(k_5);
		arrayList.add(k_6);
		arrayList.add(k_7);
		arrayList.add(k_8);
		arrayList.add(k_9);
	}

	@Override
	public RawToken tryCreateToken(BufferCharQueue bufferCharQueue) throws GrammarError {
		for (int idx = 0; idx < arrayList.size(); ++idx) {
			String[] k_x = arrayList.get(idx);
			if (k_x.length <= 0) {
				continue;
			}
			String str = bufferCharQueue.peekN(idx + 1);
			for (String k : k_x) {
				if (k.equals(str)) {
					if (testTail(bufferCharQueue)) {
						bufferCharQueue.eatN(idx + 1);
						return new RawToken(k, RawTokenType.KEYWORD);
					} else {
						bufferCharQueue.back(idx + 1);
						break;
					}
				}
			}
		}
		return null;
	}

	private boolean testTail(BufferCharQueue bufferCharQueue) throws GrammarError {
		char tail = bufferCharQueue.peekChar();
		if (tail >= '0' && tail <= '9') {
			bufferCharQueue.back(1);
			return false;
		}
		if (tail >= 'a' && tail <= 'z') {
			bufferCharQueue.back(1);
			return false;
		}
		if (tail >= 'A' && tail <= 'Z') {
			bufferCharQueue.back(1);
			return false;
		}
		bufferCharQueue.back(1);
		return true;
	}
}